<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>SVG to Image</title>
        <style>
            .content{
                border: 1px solid greenyellow;
                height: 500px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 14px;
            }

        </style>
    </head>
    <body>
        <h1>SVG to Image</h1>
        <div class="content">
            拖拽文件
        </div>
        <script>
            const content=document.getElementsByClassName('content')[0]
            content.addEventListener('dragenter',onDrag)
            content.addEventListener('dragover',onDrag)
            content.addEventListener('drop',onDrop)
            const allChildNodes = (node) => {
  var allCN = [];
  var getAllChildNodes = function (node, allCN) {
    var nodes = node.childNodes;
    for (var i = 0; i < nodes.length; i++) {
      var child = nodes[i];
      allCN.push(child);
      getAllChildNodes(child, allCN);
    }
  }
  getAllChildNodes(node, allCN);
  return allCN;
}
        const uploadFile=async(e)=>{
            const readFile = (oFile) => {
            return new Promise((resolve, reject) => {
                const extName = oFile.name
            .substring(oFile.name.lastIndexOf("."))
            .toLowerCase();
            if ([".svg"].includes(extName)) {
                console.log(oFile)
                const reader = new FileReader();
            //读取成功
            reader.onload = () => {};
            reader.onloadstart = () => {};
            reader.onloadend = () => {
              const xmlDoc = new DOMParser().parseFromString(
                reader.result,
                "text/xml"
              );
              if (xmlDoc) {
                let svgs = xmlDoc.getElementsByTagName("svg");
                if (svgs.length > 0) {
                  const svg = svgs[0];
                  const content = svg.innerHTML;
                  const nodes = allChildNodes(svg);
                  let filename = oFile.name;
                  for (let node of nodes) {
                    var tagName = String(node.tagName).toLowerCase();
                    if (
                      tagName == "title"
                    ) {
                        if(
                            node.innerHTML
                        ){
                            filename=node.innerHTML+'.png'
                        }
                    }
                }
                var image = new Image();
                var svgData = new XMLSerializer().serializeToString( svg );
                image.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svgData ))); //给图片对象写入base64编码的svg流
                console.log(image.src)
                console.log(image.complete)
                image.onload=()=>{
                    const canvas = document.createElement('canvas');  //准备空画布
                    canvas.width = svg.width.animVal.value;
                    canvas.height = svg.height.animVal.value;
                    var ctx = canvas.getContext('2d');  //取得画布的2d绘图上下文
                    ctx.drawImage(image, 0, 0);

                    var a = document.createElement('a');
                    a.href = canvas.toDataURL('image/png');  //将画布内的信息导出为png图片数据
                    a.download = filename;  //设定下载名称
                    a.click(); //点击触发下载

                }
                resolve();
              
                }
              }
            };
            reader.onabort = () => {
              console.log("中断");
            };
            reader.onerror = () => {
              console.log("读取失败");
            };
            reader.onprogress = (ev) => {
              const scale = ev.loaded / ev.total;
              if (scale >= 0.5) {
                reader.abort();
              }
            };
            reader.readAsText(oFile);
            }


            resolve();
            });
      };

      for (let oFile of e.target.files) {
        await readFile(oFile);
      }
        }



        async function onDrop(e) {
      e.stopPropagation();
      e.preventDefault();
            if (!e?.dataTransfer?.files.length) {
                return;
            }
            const files = e.dataTransfer.files;
            uploadFile({
                target: {
                files: files,
                },
            });
            }
        function onDrag(e) {
      e.stopPropagation();
      e.preventDefault();
    }
    </script>
    </body>
</html>
